import AgoraRTC from './AgoraRTC.js'
import AgoraRTS from './AgoraRTS.js'

const rtc = {
    client: null,
    joined: false, //是否已经加入频道
    published: false, // 是否已经发布
    localStream: null,
    remoteStreams: [],
    params: {}
};

const agoraFunction = function(that,option){
	if(rtc.joined){
		console.log("您已经加入频道");
		return
	}
	// 创建客户端
	rtc.client = AgoraRTC.createClient({mode: "live", codec: "vp8"});
	rtc.params = {mode:'live', codec: 'vp8'}; // 赋值输入框的值
	Listening(that);// 开始监听
	// 初始化
	rtc.client.init(option.appID,function(){
		//加入频道
		rtc.client.join(option.token ? option.token : null, option.channel, option.uid ? +option.uid : null,function(uid){
			  rtc.joined = true;
			  rtc.params.uid = uid;   // 获取到自己的id
			  if(that.option.class_type==1) return
			  createStream();// 创建本地流
		},function(err){
			console.log("加入频道失败",err)
		})
		
	},(err)=>{
		console.log(err)
	})
}

const createStream = function(){//创建本地流
	rtc.localStream = AgoraRTC.createStream({
		streamID: rtc.params.uid, // 在上一步获取到的自己的视频id
		audio: true,
		video: true,
		screen: false, // 是不是需要共享屏幕
	});
	console.log(rtc.localStream)
	// 初始化本地流
	rtc.localStream.setVideoProfile("360p_1"); //  640X360  15  400 视频清晰度
	rtc.localStream.init(function () {
	    // 发布本地流
	    rtc.localStream.play('local_stream'); // 插入到这个id中
	    publish(); // 发布本地流
	}, function (err) {
	    console.error("本地流-初始化-失败", err);
	});
}

// 发布本地流
const publish =  function () { // 发布本地流
    if (!rtc.client) {
      console.log('您还没加入频道')
      return;
    }
    if (rtc.published) {
      console.log("您已经发布频道")
      return;
    }
    const oldState = rtc.published;

    rtc.client.publish(rtc.localStream, function (err) {
      rtc.published = oldState;
      console.error(err);
    })
    rtc.published = true
}

//订阅事件
const Listening = function(that){
	rtc.client.on("err",(err)=>{
		console.log("====>",err)
	});
	// 主播加入频道
	rtc.client.on("peer-online",function(evt){
		console.log("peer-online---------------------------------------------", evt.uid);
	});
	rtc.client.on("client-role-changed",function(evt){
		if(evt.role=="host"){
			that.changeOccupy("host")
		}else if(evt.role=="audience"){
			that.changeOccupy("audience")
		}
	});
	// 有用户离开时
	rtc.client.on("peer-leave",function(evt){
		var uid = evt.uid;
		var reason = evt.reason; // 离线原因 Quit -- 主动离开  ServerTimeOut -- 超时掉线（也有可能是主动离开）
		if(uid!=rtc.params.uid){
			that.deleteView(uid);
		};
		console.log("用户离线" , uid, "reason: ", reason);
	});
	// 发布视频流本地触发
	rtc.client.on("stream-published",function(evt){
		var remoteStream = evt.stream;
		var id = remoteStream.getId();
		that.myId = id;
	});
	//有远程流加入时
	rtc.client.on("stream-added",function(evt){
		console.log(evt)
		var remoteStream = evt.stream;
		var id = remoteStream.getId();
		if(id!==rtc.params.uid){
			rtc.client.subscribe(remoteStream,function(err){ // 订阅加入的远程端视频
				console.log("订阅远程端视频失败", err);
			})
		}
		console.log('加入的远程端视频流: ', id);
	});
	rtc.client.on("stream-subscribed",function(evt){ //订阅远程流
	that.again_msg();
		var remoteStream = evt.stream;
		var id = remoteStream.getId();
		rtc.remoteStreams.push(remoteStream);
		that.addView(id);
		setTimeout(()=>{
			remoteStream.play("remote_video_"+id);// 插入到id为remote_video_的元素中
		},1000)
		 console.log('接收到的远程端视频: ', id);
	});
	rtc.client.on("stream-removed",function(evt){ // 对方取消发布
		var remoteStream = evt.stream;
		var id = remoteStream.getId();
		remoteStream.stop("remote_video_" + id);
		rtc.remoteStreams = rtc.remoteStreams.filter(function(stream){
			return stream.getId() !== id;
		})
		that.deleteView(id);
	});
	rtc.client.on("onTokenPrivilegeWillExpire",function(){
		console.log("token即将过期")
	});
	rtc.client.on("onTokenPrivilegeDidExpire",function(){
		 console.log("token已经失效");
	});
	rtc.client.on("mute-audio",function(evt){ // 对方关闭了语音
		var uid = evt.uid;
		console.log("mute audio:" + uid);
	});
	rtc.client.on("unmute-audio",function(evt){ // 对方打开了语音
		var uid = evt.uid;
		console.log("unmute audio:" + uid);
	});
	rtc.client.on("mute-video",function(evt){ // 对方关闭摄像头
		var uid = evt.uid;
		console.log("mute video" + uid);
	});
	rtc.client.on("unmute-video", function (evt){ // 对方打开摄像头
		var uid = evt.uid;
		console.log("mute video" + uid);
	});
}

const leave = function(){ //离开频道
	if (!rtc.client) {
		console.log("您还没加入频道")
		return;
	}
	if (!rtc.joined) {
		console.log("您还没加入频道")
		return;
	}
	rtc.client.leave(function(){
		if(rtc.localStream!=null){
			rtc.localStream.stop();
			rtc.localStream.close();
		}
		
		while(rtc.remoteStreams.length>0){
			var stream = rtc.remoteStreams.shift();
			var id = stream.getId();
			stream.stop();
		}
		rtc.localStream = null;
		rtc.remoteStreams = [];
		rtc.client = null;
		rtc.published = false;
		rtc.joined = false;
		console.log("离开频道成功")
	},function(err){
		console.log('离开频道失败',err)
	})
}

function unpublish(rtc){
	if(!rtc.client){
		console.log("您还没加入频道")
		return
	}
	if(!rtc.published){
		console.log("您已经发布频道")
		return
	}
	var oldState = rtc.published;
	rtc.client.unpublish(rtc.localStream,function(err){
		rtc.published = oldState;
		console.error(err);
	})
	console.log("取消发布成功");
	rtc.published = false;
}


export default {
    rtc, // 参数
    agoraFunction, // 声网开始的方法  创建  初始化 加入频道 
    publish, // 发布本地流
    unpublish, // 停止发布本地流
    leave, // 离开频道
	createStream, //创建本地流
};

